﻿var richTextIsChange = false;
var timeTooltipInvisible = 2000;
var timerTooltipID;
var timerSuggestionID;
var timerSugguestionRequest;
var timeWaitingSuggestion = 200;
var maxWordsSearch = 4;
var isTooltipVisible = false;
var isSuggestionVisible = false;
var sugguestionLines = null;
var sugguestionLineFound = 0;
var sugguestionLineNumberReduce = 0;
var sugguestionLineNumberIncrease = 0;
var defaultSugguestionLinesReduce = 2;
var defaultSugguestionLinesIncrease = 2;
var isLessThan40Words = null;
var yearQuotation;
var uploaderQuotaion;
var mouseInsideTooltip = false;
var startDectectTooltipInside = false;

var arrFunctionKeysCode = [ 9, 13, 16, 17, 18, 19, 20, 27, 32, 33, 34, 35, 36,
		37, 38, 39, 40, 44, 91, 112, 113, 114, 115, 116, 117, 118, 119, 120,
		121, 122, 123, 144, 145, 192 ];

$(function() {
	breaking();

	$("#richTextBox").mouseenter(function() {
		if (richTextIsChange) {
			breaking();
		}
	}).keyup(function() {
		richTextIsChange = true;
	}).blur(function() {
		if (richTextIsChange) {
			breaking();
		}
	});

	// bound event tooltip
	$("#tooltip").mouseover(function() {
		startDectectTooltipInside = false;
		//mouseInsideTooltip = true;
		clearTimeout(timerTooltipID);
	}).mouseleave(function() {
		startDectectTooltipInside = true;
		//mouseInsideTooltip = false;
		//timerTooltipID = setTimeout("closeTooltip();", timeTooltipInvisible);
	});

	$("#tooltip-toolbar-close").click(function() {
		closeTooltip();
	});

	$("#suggestion").mouseover(function() {
		//clearTimeout(timerSuggestionID);
	}).mouseleave(function() {
		// timerSuggestionID = setTimeout("closeSuggestion();",
		// timeTooltipInvisible);
	});

	$("#suggestion-toolbar-close").click(function() {
		closeSuggestion();
	});
	
	$(document).mouseover(function(){
		if (!mouseInsideTooltip && startDectectTooltipInside)
		{
			startDectectTooltipInside = false;
			clearTimeout(timerTooltipID);
			timerTooltipID = setTimeout("closeTooltip();", timeTooltipInvisible);
		}
	});	

	/*
	 * $(document).click(function(e) { var x = e.pageX; var y = e.pageY; var
	 * isOutside = false;
	 * 
	 * if (isTooltipVisible){ var tooltip = $("#tooltip"); var offsetTootip =
	 * tooltip.offset(); isOutside = false; if (x < offsetTootip.left || x >
	 * offsetTootip.left + tooltip.width()) { isOutside = true; } else if (y <
	 * offsetTootip.top || y > offsetTootip.top + tooltip.height()) { isOutside =
	 * true; }
	 * 
	 * if (isOutside) { closeTooltip(); } }
	 * 
	 * if (isSuggestionVisible){ var suggestion = $("#suggestion"); var
	 * offsetSuggestion = suggestion.offset(); isOutside = false; if (x <
	 * offsetSuggestion.left || x > offsetSuggestion.left + suggestion.width()) {
	 * isOutside = true; } else if (y < offsetSuggestion.top || y >
	 * offsetSuggestion.top + suggestion.height()) { isOutside = true; }
	 * 
	 * if (isOutside) { closeSuggestion(); } } });
	 */

	var widthScreen = getWindowWidth();
	var height = getWindowHeight();
	var sugguestion = $("#suggestion");
	var x = (widthScreen - sugguestion.width()) / 2;
	var y = (height - sugguestion.height()) / 2;
	sugguestion.css( {
		left : x + "px",
		top : y + "px"
	});
	/*
	clip = new ZeroClipboard.Client();
	clip.glue('copySugguestion');
	clip.addEventListener('mouseDown', function() {		
		var strPage = $("#quotePage").val();
		var page = 0;
		if (isNaN(strPage) || $.trim(strPage) == "0") {
			alert("Please enter your quotation page number");
			$("#quotePage").focus();
		} else {
			page = parseInt(strPage);
			var text = $("#spSuggestionContent").text();
			if (isLessThan40Words) {
				if ($("#less40wordsCaseA input").attr('checked')) {
					text = text + " (" + uploaderQuotaion + "," + yearQuotation
							+ ",p." + page + ")";
				} else if ($("#less40wordsCaseB input").attr('checked')) {
					text = uploaderQuotaion + " " + text + "(" + yearQuotation
							+ ",p." + page + ")";
				} else if ($("#less40wordsCaseC input").attr('checked')) {
					text = uploaderQuotation + "(" + yearQuotation + ") "
							+ text + "(p." + page + ")";
				}				
			} else {
				text = text + ".(" + uploaderQuotaion + "," + yearQuotation
						+ ",p." + page + ")";
			}			
			// copy into clipboard
			clip.setText(text);
			//alert(text);
			closeSuggestion();
		}
	});
	*/
});

ZeroClipboard.setMoviePath('ZeroClipboard.swf');
var clip = null;

function breaking() {	
	var richTextBox = document.getElementById("richTextBox");
	var nodes = getTextNodesIn(richTextBox);
	for ( var i = 0; i < nodes.length; i++) {
		var text = $(nodes[i]).text();
		if (text != "") {
			if (nodes[i].parentNode.tagName == "SPAN"
					&& nodes[i].nextSibling == null
					&& nodes[i].previousSibling == null) {
				//$(nodes[i].parentNode).replaceWith(breakingWords(text));
				$(nodes[i].parentNode).html(breakingWords(text));
			} else {
				text = text.replace(/^\n*\s*/, "");
				if (text != "") {
					$(nodes[i]).replaceWith(breakingWords(text));
				}
			}
		}
	}

	$(".tooltip-word").mouseover(function() {
		loadDefinitionOfTerm(this);
	});
	richTextIsChange = false;
	setFocusEditable();
}

function getTextWithoutMark(tag, isNoTrim) {
	var text = $(tag).text().toLowerCase();
	if (!isNoTrim)
	{
		text = $.trim(text);
	}
	// remove redundacy characters at the begin
	text = text.replace(/^\.|,|\?|>|<|"|'|;|:|\(/, "");
	// remove redundacy characters at the end
	text = text.replace(/\.|,|\?|>|<|"|'|;|:|\)$/, "");
	// searching in you DB by using ajax and get json response
	// in this case i use db in client machine. i store it at the end of the
	// file
	return text;
}

var MAX_WORDS_TOOLTIP = 3;

// /load definition of term
// /return true if the definition has found. otherwise false
function loadDefinitionOfTerm(term) {
	if (arrTerms != null && arrTerms.length > 0) {
		var current = term;
		/** ****************************************************************************************************************** */
		var arrWordsSearch = new Array();
		var temp = term;
		var text = "";
		var word = "";
		if (MAX_WORDS_TOOLTIP >= 1) {
			text = getTextWithoutMark(temp, true);
			word = text;
			arrWordsSearch.push(text);
		}

		if (MAX_WORDS_TOOLTIP >= 2) {
			if (temp.previousSibling && temp.previousSibling.previousSibling) {
				text = getTextWithoutMark(temp.previousSibling.previousSibling, true) + getTextWithoutMark(temp.previousSibling, true);
				arrWordsSearch.push(text
						+ arrWordsSearch[arrWordsSearch.length - 1]);
				if (MAX_WORDS_TOOLTIP >= 3) {
					temp = temp.previousSibling.previousSibling;
					if (temp && temp.previousSibling && temp.previousSibling.previousSibling) {
						text = getTextWithoutMark(temp.previousSibling.previousSibling, true) + getTextWithoutMark(temp.previousSibling, true);
						arrWordsSearch.push(text
								+ arrWordsSearch[arrWordsSearch.length - 1]);
					}
				}
			}

			temp = current;

			if (temp.nextSibling && temp.nextSibling.nextSibling) {
				text = getTextWithoutMark(temp.nextSibling, true) + getTextWithoutMark(temp.nextSibling.nextSibling, true);
				arrWordsSearch.push(word + text);

				if (MAX_WORDS_TOOLTIP >= 3) {
					temp = temp.nextSibling.nextSibling;
					if (temp.nextSibling && temp.nextSibling.nextSibling) {
						text = getTextWithoutMark(temp.nextSibling, true) + getTextWithoutMark(temp.nextSibling.nextSibling, true);
						arrWordsSearch.push(arrWordsSearch[arrWordsSearch.length - 1] + text);
					}
				}
			}
			
			temp = current;
			if (MAX_WORDS_TOOLTIP >= 3)
			{
				if (temp.previousSibling && temp.previousSibling.previousSibling && temp.nextSibling && temp.nextSibling.nextSibling)
				{
					text = getTextWithoutMark(temp.previousSibling.previousSibling, true) + getTextWithoutMark(temp.previousSibling, true) +
							word + getTextWithoutMark(temp.nextSibling, true) + getTextWithoutMark(temp.nextSibling.nextSibling, true);
					arrWordsSearch.push(text);
				}
			}
		}

		var found = false;
		for ( var k = 0; k < arrWordsSearch.length && !found; k++) {
			text = $.trim(arrWordsSearch[k]).toLowerCase();
			// loop
			for ( var i = 0; i < arrTerms.length; i++) {
				if (text == arrTerms[i]) {
					$.getJSON('search_term.php?term=' + escape(text), function(
							data) {
						if (data.found) {
							$("#tooltipHeader").text(text);
							$("#tooltipDefinition").html(data.definition);
							$("#tooltipLink").attr('href', data.url).text(
									data.url);
							showTooltip(term);
							// clearTimeout(timerTooltipID);
							// timerTooltipID = setTimeout("closeTooltip();",
							// timeTooltipInvisible);
						}
					});
					found = true;
					break;
				}
			}
		}
	}
}

function showTooltip(term) {
	clearTimeout(timerTooltipID);
	var offset = $(term).offset();
	var tooltip = $("#tooltip");
	var windowWidth = $(document).width();// getWindowWidth();
	var windowHeight = $(document).height();// getWindowHeight();
	var tooltipWidth = tooltip.width();
	var tooltipHeight = tooltip.height();
	var x, y;
	// check width screen is still available for display
	var margin = 20;
	var isLeftShowing = true;
	var isTopShowing = true;
	if (offset.left + tooltipWidth < windowWidth) {
		x = offset.left;
	} else {
		x = offset.left - tooltipWidth;
		isLeftShowing = false;
	}
	
	if (offset.top + tooltipHeight + margin < windowHeight) {
		y = offset.top + margin;
	} else {
		y = offset.top - tooltipHeight - margin;
		isTopShowing = false;
	}
	
	$("#tooltipTopLeft").hide();
	$("#tooltipTopRight").hide();
	$("#tooltipBottomLeft").hide();
	$("#tooltipBottomRight").hide();
	
	if (isLeftShowing)
	{
		if (isTopShowing)
		{
			$("#tooltipTopLeft").show();
		}
		else
		{
			$("#tooltipBottomLeft").hide();
		}
	}
	else
	{
		if (isTopShowing)
		{
			$("#tooltipTopRight").show();
		}
		else
		{
			$("#tooltipBottomRight").hide();
		}
	}
	
	
	isTooltipVisible = true;
	tooltip.css( {
		left : x + "px",
		top : y + "px"
	}).fadeIn(function(){
		startDectectTooltipInside = true;
	});
}

function showSuggestion(term) {
	
	/*
	 * var offset = $(term).offset(); var tooltip = $("#suggestion"); var
	 * windowWidth = $(document).width();//getWindowWidth(); var windowHeight =
	 * $(document).height();// getWindowHeight(); var tooltipWidth =
	 * tooltip.width(); var tooltipHeight = tooltip.height(); var x, y; // check
	 * width screen is still available for display var margin = 20; if
	 * (offset.left + tooltipWidth < windowWidth) { x = offset.left; } else { x =
	 * offset.left - tooltipWidth; }
	 * 
	 * if (offset.top + tooltipHeight + margin < windowHeight) { y = offset.top +
	 * margin; } else { y = offset.top - tooltipHeight - margin; }
	 * isSuggestionVisible = true; tooltip.css( { left : x + "px", top : y +
	 * "px" }).fadeIn();
	 */
	//clip.show();	
	var tooltip = $("#suggestion").css('visibility', 'visible');
	$("#quotePage").focus();
	// clip.reposition();
}

function breakingWords(text) {
	if (text.length == 1) {
		return "<span>" + text + "</span>";
	} else {
		text = text.replace(/&nbsp;/, " ");
		var result = "";
		var isReadText = text.charAt(0) != " " && text.charCodeAt(0) != 160;
		var i = 0, k = 0;
		var start = 0;

		while (i < text.length) {
			k = i;
			if (isReadText) {
				while (i < text.length && text.charAt(i) != ' '
						&& text.charCodeAt(0) != 160) {
					i++;
				}
				isReadText = false;
			} else {
				while (i < text.length
						&& (text.charAt(i) == ' ' || text.charCodeAt(i) == 160)) {
					i++;
				}
				isReadText = true;
			}
			var temp = text.substring(start, i);
			if (!isReadText) {
				result += "<span class='tooltip-word'>" + htmlEncode(temp) + "</span>";
			} else {
				result += "<span>" +  htmlEncode(temp) + "</span>";
			}
			start = i;
			if (k == i) {
				i++;
			}
		}
	}

	return result;
}

function htmlEncode(value)
{
	if (value)
		return $('<div/>').text(value).html();
	else
		return value;
}

function getTextNodesIn(node, includeWhitespaceNodes) {
	var textNodes = [];

	function getTextNodes(node) {
		if (node.nodeType == 3) {
			textNodes.push(node);
		} else {
			for ( var i = 0, len = node.childNodes.length; i < len; ++i) {
				getTextNodes(node.childNodes[i]);
			}
		}
	}

	getTextNodes(node);
	return textNodes;
}

function getWindowWidth() {
	var width = 0;
	if (window.innerWidth) {
		width = window.innerWidth;
	} else if (document.documentElement && document.documentElement.clientWidth) {
		width = document.documentElement.clientWidth;
	} else if (document.body) {
		width = document.body.clientWidth;
	}
	return width;
}

function getWindowHeight() {
	var theHeight = 0;
	if (window.innerHeight) {
		theHeight = window.innerHeight;
	} else if (document.documentElement
			&& document.documentElement.clientHeight) {
		theHeight = document.documentElement.clientHeight;
	} else if (document.body) {
		theHeight = document.body.clientHeight;
	}
	return theHeight;
}

function closeTooltip() {
	if (isTooltipVisible) {
		isTooltipVisible = false;
		$('#tooltip').fadeOut(function(){
			startDectectTooltipInside = false;
		});
		clearTimeout(timerTooltipID);
	}
	mouseInsideTooltip = false;
	startDectectTooltipInside = false;
}

function closeSuggestion() {
	$('#suggestion').css('visibility', 'hidden');
	//clip.hide();
	if (isSuggestionVisible) {
		isSuggestionVisible = false;
		// $('#suggestion').fadeOut();
		$('#suggestion').css('visibility', 'hidden');
		// clearTimeout(timerSuggestionID);
	}
}

// this is an array of terms that has definition.
// load all terms
var arrTerms = null;
$(function() {
	$.getJSON("all_terms.php", function(data) {
		arrTerms = data.terms;
	});
});

function searchRelevantAssigment()
{
	if ($("#assignment_title").val() != "")
	{
		$("#loadingDataAjax").fadeIn();
		$.get('/journaldata/search.php?type=compose_assigment&text=' + escape($("#assignment_title").val()),
			function(e){								
				$("#loadingDataAjax").fadeOut();
				$("#divEmptyData").html(e).addClass("relevantAssigment").fadeIn();
			}
		);
	}
	else
	{
		alert("Please enter your assigment title");
		$("#assignment_title").focus();
	}
}
var captureSelection = function(e) {
	if (!e)
		e = window.event;

	if ($.inArray(e.keyCode, arrFunctionKeysCode) == -1
			|| (e.ctrl && (e.keyCode != 67 || e.keyCode != 86))) {
		var currentNode = null;
		if (window.getSelection) {
			currentNode = window.getSelection().focusNode;
			if (currentNode && currentNode.nodeType == 3) {
				currentNode = currentNode.parentNode;
			}
		} else if (document.selection && document.selection.createRange) {
			currentNode = document.selection.createRange().parentElement();
			// if (currentNode && currentNode.nodeType == 3)
			// {
			// currentNode = currentNode.parentElement();
			// }
		} else {
			// doesnt support others
			return;
		}

		if (currentNode) {
			var arrWords = new Array();
			var text = $(currentNode).text();
			var isEnoughWordsFirstTime = false;
			arrWords = getWords(text);
			if (arrWords.length < maxWordsSearch) {
				var tempNode = currentNode;
				/*
				 * while (arrWords.length < maxWordsSearch &&
				 * tempNode.previousSibling) { tempNode =
				 * tempNode.previousSibling; if (tempNode.tagName == "BR") {
				 * break; } text = $(tempNode).text(); var arrTemp =
				 * getWords(text); if (arrTemp.length > 0) { for ( var i =
				 * arrTemp.length - 1; i >= 0 && arrWords.length <
				 * maxWordsSearch; i--) { arrWords.push(arrTemp[i]); } } }
				 */
				/*
				while (arrWords.length < maxWordsSearch) {
					var tNode = tempNode;
					tempNode = tempNode.previousSibling;
					if (!tempNode) {
						if (tNode.parentNode.tagName == "SPAN") {
							tempNode = tNode.parentNode;
							if (tempNode.id == "richTextBox") {
								break;
							}
							continue;
						}
					}
					if (tempNode.tagName == "BR") {
						break;
					}
					text = $(tempNode).text();
					var indexDot = text.indexOf('.');
					if (indexDot >= 0) {
						text = text.substring(indexDot, text.length - 1);
					}
					var arrTemp = getWords(text);
					if (arrTemp.length > 0) {
						for ( var i = arrTemp.length - 1; i >= 0
								&& arrWords.length < maxWordsSearch; i--) {
							arrWords.push(arrTemp[i]);
						}
					}
					if (indexDot >= 0) {
						break;
					}
				}
				*/
				
				arrWords = new Array();
				var textResult = $(currentNode).text();				
				while (countWordsInText(textResult) < maxWordsSearch) {
					var tNode = tempNode;
					tempNode = tempNode.previousSibling;
					if (!tempNode) {
						if (tNode.parentNode.tagName == "SPAN") {
							tempNode = tNode.parentNode;
							if (tempNode.id == "richTextBox") {
								break;
							}
							continue;
						}
					}
					if (!tempNode || tempNode.tagName == "BR") {
						break;
					}
					text = $(tempNode).text();
					var indexDot = text.indexOf('.');
					if (indexDot >= 0) {
						text = text.substring(indexDot, text.length - 1);
					}
					
					textResult = text + textResult; 
					if (indexDot >= 0) {
						break;
					}
				}
				
				textResult = $.trim(textResult);
				var tempTextResult = "";				
				//replace 160
				for(var i = 0; i < textResult.length; i++)
				{
					if (textResult.charCodeAt(i) == 160)
					{
						tempTextResult += ' ';
					}
					else
					{
						tempTextResult += textResult.charAt(i);
					}
				}				
				var arrTemp = tempTextResult.split(' ');
				for(var i = arrTemp.length - 1; i >=0 && arrWords.length < maxWordsSearch;i--)
				{
					if (arrTemp[i] != '')
					{
						arrWords.push(arrTemp[i]);
					}
				}				
			} else {
				isEnoughWordsFirstTime = true;
			}
			
			// clearTimeout(timerSugguestionRequest);
			if (arrWords.length == maxWordsSearch) {
				var term = "";
				if (!isEnoughWordsFirstTime) {
					for ( var i = 0; i < maxWordsSearch; i++) {
						term += arrWords.pop() + " ";
					}
				} else {
					term = arrWords.join(" ");
				}
				term = $.trim(term);
				var tailURL = new Date().getTime();
				// timerSugguestionRequest = setTimeout(function(){
				$.getJSON("search_pdf_term.php?term=" + term + "&t=" + tailURL, function(data) {
					// var data = $.parseJSON(args);
					var tooltipUrl = $("#suggestionUrls");
					if (data.found) {
						tooltipUrl.html("");
						$("#suggestionHeader").text("Suggestion");
						sugguestionLines = data.content.split('.');
						yearQuotation = data.year;
						uploaderQuotaion = data.uploader;
						loadDefaultSugguestionText(term);
						if (sugguestionLineFound != -1)
						{
							showSuggestion(currentNode);
							
							clip = new ZeroClipboard.Client();
							clip.glue('copySugguestion');
							clip.addEventListener('mouseDown', function() {		
								var strPage = $("#quotePage").val();
								var page = 0;
								if (isNaN(strPage) || $.trim(strPage) == "0") {
									alert("Please enter your quotation page number");
									$("#quotePage").focus();
								} else {
									page = parseInt(strPage);
									var text = $("#spSuggestionContent").text();
									if (isLessThan40Words) {
										if ($("#less40wordsCaseA input").attr('checked')) {
											text = text + " (" + uploaderQuotaion + "," + yearQuotation
													+ ",p." + page + ")";
										} else if ($("#less40wordsCaseB input").attr('checked')) {
											text = uploaderQuotaion + " " + text + "(" + yearQuotation
													+ ",p." + page + ")";
										} else if ($("#less40wordsCaseC input").attr('checked')) {
											text = uploaderQuotation + "(" + yearQuotation + ") "
													+ text + "(p." + page + ")";
										}				
									} else {
										text = text + ".(" + uploaderQuotaion + "," + yearQuotation
												+ ",p." + page + ")";
									}			
									// copy into clipboard
									clip.setText(text);
									//alert(text);
									closeSuggestion();
								}
							});
						}						
					} else {
						closeSuggestion();
					}
				});
				// }, timeWaitingSuggestion);
			}
		}
	} else {
		// clearTimeout(timerSugguestionRequest);
		closeSuggestion();
	}
};

function getWords(text) {
	var arr = new Array();
	if (text && text != "") {
		text = $.trim(text);
		var length = text.length;
		var word = '';

		for ( var i = 0; i < length; i++) {
			if (text.charAt(i) != ' ' && text.charAt(i) != '\t'
					&& text.charAt(i) != '\n' && text.charCodeAt(0) != 160) {
				word += text.charAt(i);
			} else if ((text.charAt(i) == ' ' || text.charAt(i) == '\t'
					|| text.charAt(i) == '\n' || text.charCodeAt(0) == 160)
					&& word != '') {
				arr.push(word);
				word = '';
				if (arr.length >= maxWordsSearch) {
					break;
				}
			}

			if (i == length - 1 && word != '') {
				arr.push(word);
			}
		}
	}
	while (arr.length > maxWordsSearch) {
		arr.pop();
	}
	return arr;
}

$(function() {
	var editable = document.getElementById('richTextBox');
	editable.onkeyup = captureSelection;
	$("#addLineBefore").click(function() {
		if (sugguestionLineNumberReduce > 0) {
			sugguestionLineNumberReduce--;
			loadSuggestionTextFromLineToLine();
		}
	});

	$("#reduceLineBefore").click(function() {
		if (sugguestionLineNumberReduce < sugguestionLineFound) {
			sugguestionLineNumberReduce++;
			loadSuggestionTextFromLineToLine();
		}
	});

	$("#addLineAfter").click(function() {
		if (sugguestionLineNumberIncrease < sugguestionLines.length - 1) {
			sugguestionLineNumberIncrease++;
			loadSuggestionTextFromLineToLine();
		}
	});

	$("#reduceLineAfter").click(function() {
		if (sugguestionLineNumberIncrease > sugguestionLineFound + 1) {
			sugguestionLineNumberIncrease--;
			loadSuggestionTextFromLineToLine();
		}
	});

});

function loadDefaultSugguestionText(textSearch) {
	sugguestionLineFound = -1;
	var text = textSearch.toLowerCase();
	if (sugguestionLines && sugguestionLines.length > 0) {
		var length = sugguestionLines.length;
		for ( var i = 0; i < length; i++) {
			var line = sugguestionLines[i].toLowerCase();
			if (line.indexOf(text) != -1) {
				sugguestionLineFound = i;
				sugguestionLineNumberIncrease = sugguestionLineFound
						+ defaultSugguestionLinesIncrease;
				if (sugguestionLineNumberIncrease >= length) {
					sugguestionLineNumberIncrease = length - 1;
				}
				sugguestionLineNumberReduce = sugguestionLineFound
						- defaultSugguestionLinesReduce;
				if (sugguestionLineNumberReduce < 0) {
					sugguestionLineNumberReduce = 0;
				}
				loadSuggestionTextFromLineToLine();
				break;
			}
		}
	}
}

function countWordsInText(text)
{
	var arrTemp = text.split(' ');
	var countWords = 0;
	for ( var i = 0; i < arrTemp.length; i++) {
		if ($.trim(arrTemp[i]) != '') {
			countWords++;
		}
	}
	return countWords;
}

function loadSuggestionTextFromLineToLine() {
	var text = "";
	var textCount = "";
	for ( var i = sugguestionLineNumberReduce; i < sugguestionLineNumberIncrease; i++) {
		if (i == sugguestionLineFound) {
			text += "<span class='text-found'>" + sugguestionLines[i]
					+ "</span>.";
		} else {
			text += sugguestionLines[i] + ".";
		}
		textCount += sugguestionLines[i] + ".";
	}

	if (text != "") {
		text = text.substring(0, text.length - 1);
		textCount = textCount.substring(0, textCount.length - 1);
		// count words		
		var countWords = countWordsInText(textCount);
		$("#wordsSuggestion").text(countWords);
	}

	if (isLessThan40Words == null || isLessThan40Words != (countWords < 40)) {
		$("#quoteFormats").html("");
		isLessThan40Words = countWords < 40;
		var currentPage = 0;
		if ($("#quotePage").length > 0) {
			currentPage = $("#quotePage").val();
		}

		if (countWords < 40) {
			text = "\"" + text + "\"";
			$("#quoteHeader").html("");
			$("#quoteFooter").html(
					"(" + uploaderQuotaion + "," + yearQuotation
							+ ",p.<input type='text' value='" + currentPage
							+ "' id='quotePage'>)");
			$("#quoteFormats")
					.append(
							'<label id="less40wordsCaseA"><input type="radio" name="quoteGroupForm" checked="checked"/><span class="option-format"">a)</span> "......"(Name, Year,p.)</label>');
			$("#less40wordsCaseA").click(
					function() {
						$("#quoteHeader").html("");
						$("#quoteFooter").html(
								"(" + uploaderQuotaion + "," + yearQuotation
										+ ",p.<input type='text' value='"
										+ currentPage + "' id='quotePage'>)");
					});
			$("#quoteFormats")
					.append(
							'<label id="less40wordsCaseB"><input type="radio" name="quoteGroupForm"/><span class="option-format"">b)</span> Name "......"(Year,p.)</label>');
			$("#less40wordsCaseB").click(
					function() {
						$("#quoteHeader").html(uploaderQuotaion + " ");
						$("#quoteFooter").html(
								"(" + yearQuotation
										+ ",p.<input type='text' value='"
										+ currentPage + "' id='quotePage'>)");
					});
			$("#quoteFormats")
					.append(
							'<label id="less40wordsCaseC"><input type="radio" name="quoteGroupForm"/><span class="option-format"">c)</span> Name(Year) "......"(p.)</label>');
			$("#less40wordsCaseC").click(
					function() {
						$("#quoteHeader").html(
								uploaderQuotaion + "(" + yearQuotation + ") ");
						$("#quoteFooter").html(
								"(p.<input type='text' value='" + currentPage
										+ "' id='quotePage'>)");
					});
		} else {
			$("#quoteHeader").html("");
			$("#quoteFooter").html(
					".(" + uploaderQuotaion + "," + yearQuotation
							+ ",p.<input type='text' value='" + currentPage
							+ "' id='quotePage'>)");
			$("#quoteFormats")
					.append(
							'<label id="more40wordsCaseA"><input type="radio" name="quoteGroupForm" checked="checked"/>.....<span style="color:blue">.</span>(Name,Year,p.)</label>');
			$("#more40wordsCaseA").click(
					function() {
						$("#quoteHeader").html("");
						$("#quoteFooter").html(
								".(" + uploaderQuotaion + "," + yearQuotation
										+ ",p.<input type='text' value='"
										+ currentPage + "' id='quotePage'>)");
					});
		}
	}

	$("#spSuggestionContent").html(text);
	// clip = new ZeroClipboard.Client();
}